from PyQt5.QtWidgets import QListWidgetItem

from mock import MessengerAPI

from db.message import Message
from db.chat import Chat
from db.session import session

from mock import test_chat as support_chat

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMessageBox

from interface.interface import Ui_MainWindow

from logging import getLogger
import logging

from utils import check_ip_validity, render_msgs

logging.basicConfig(level=logging.DEBUG)
log = getLogger("App")


class App(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, messenger: MessengerAPI):
        super().__init__()
        self.setupUi(self)
        self.messenger = messenger

        self.chat_bar = ChatBarManager(self)
        self.msg_zone = MsgZoneManager(self)

        # Add signals
        self.sendButton.clicked.connect(self.send)
        self.chatList.itemActivated.connect(self.select_chat)
        self.addContactButton.clicked.connect(self.add_contact)

    def send(self):
        """Signal emitter. Run when click send msg"""
        msg_text = self.messageText.toPlainText()
        msg = Message(text=msg_text, chat_id=self.chat_bar.current_chat.id, inbox=False)
        self.messenger.send_msg(to_id=self.chat_bar.current_chat.recipient, text=msg_text)
        log.info(f"Send MSG {msg_text} to {self.chat_bar.current_chat.recipient}")
        self.messageText.setPlainText("")

        session.add_model(msg)
        session.commit_session()

        self.msg_zone.update()

    def select_chat(self, chat_list_item: QListWidgetItem):
        """Signal emitter. Run when clicked on some chat name"""
        log.debug(f"Select chat {chat_list_item.text()}. Current row number: {self.chatList.currentRow()}")
        self.chat_bar.select_chat(self.chatList.currentRow())

        self.msg_zone.update()

    def add_contact(self):
        """Signal emitter. Run when click add contact button"""
        ip = self.ipInput.text()
        name = self.nameInput.text()
        self.ipInput.setText("")
        self.nameInput.setText("")
        self.ipInput.repaint()
        self.nameInput.repaint()

        self.chat_bar.add_chat(ip=ip, name=name)


class ChatBarManager:
    def __init__(self, app: App):
        self.app = app

        # Draw list with chats
        chats = [support_chat] + list(session.query(Chat).all())
        self.chats = chats
        self.chat_names = [chat.name for chat in chats]
        app.chatList.addItems(self.chat_names)
        self.current_chat = support_chat

    def add_chat(self, ip, name):
        chat = Chat(recipient=ip, name=name)
        if not check_ip_validity(ip):
            QMessageBox.warning(self.app, "Wrong IP format", "IP is not valid")
            log.info("IP is not valid")
            return False
        if not Chat.is_unique(chat):
            QMessageBox.warning(self.app, "Wrong chat name", "Such contact already exists")
            log.info("Chat is not valid")
            return False

        session.add_model(chat)
        session.commit_session()
        self.app.chatList.addItem(name)

        self.chats.append(chat)
        self.chat_names.append(chat.name)
        return True

    def select_chat(self, i):
        chat = self.chats[i]
        self.current_chat = chat


class MsgZoneManager:
    def __init__(self, app: App):
        self.app = app

    def update(self):
        # TODO тут можно оптимизировать не проверяя каждый раз БД
        msgs = list(session.query(Message).filter(Message.chat_id == self.app.chat_bar.current_chat.id))
        msgs_text = render_msgs(msgs)
        self.app.msgZone.setText(msgs_text)
        self.app.msgZone.repaint()


if __name__ == '__main__':
    # Init messenger API
    API = MessengerAPI()
    API.connect()
    log.debug("API Inited")

    # Create PyQT App
    app = QtWidgets.QApplication([])
    window = App(API)
    log.debug("Window created successfully")
    window.show()
    app.exec_()
